package com.example.girls.adapter

import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.example.girls.R
import com.example.girls.data.PhotoItem
import kotlinx.android.synthetic.main.photo_cell.view.*


class PhotoAdapter : ListAdapter<PhotoItem, PagerViewHolder>(diffCallback) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PagerViewHolder =
        PagerViewHolder.newInstance(parent)

    override fun onBindViewHolder(holder: PagerViewHolder, position: Int) {
        val photoItem = getItem(position)
        holder.bindWithPagerList(photoItem)
    }
}

class PagerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    companion object {
        fun newInstance(parent: ViewGroup): PagerViewHolder {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.photo_cell, parent, false)
            return PagerViewHolder(view)
        }
    }

    fun bindWithPagerList(photoItem: PhotoItem) {
        itemView.apply {
            shimmerLayoutPhoto.apply {
                setShimmerColor(0x55FFFFFF)
                setShimmerAngle(0)
                startShimmerAnimation()
            }
            Glide.with(this)
                .load(photoItem.url)
                .placeholder(R.drawable.ic_placeholder)
                .error(R.drawable.ic_jiazaishibai)
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        return false.also {
                            shimmerLayoutPhoto.stopShimmerAnimation()
                        }
                    }

                    override fun onResourceReady(
                        resource: Drawable?,
                        model: Any?,
                        target: Target<Drawable>?,
                        dataSource: DataSource?,
                        isFirstResource: Boolean
                    ): Boolean {
                        return false.also {
                            shimmerLayoutPhoto.stopShimmerAnimation()
                        }
                    }

                })
                .into(imageViewPhoto)
        }
    }
}